package com.industrial.white.service.impl;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.CreditCodeUtil;
import cn.hutool.core.util.IdUtil;
import com.industrial.common.core.constant.Constants;
import com.industrial.common.core.domain.R;
import com.industrial.common.core.utils.DateUtils;
import com.industrial.common.core.web.domain.AjaxResult;
import com.industrial.common.security.utils.DictUtils;
import com.industrial.common.security.utils.SecurityUtils;
import com.industrial.system.api.RemoteUserService;
import com.industrial.system.api.domain.SysRole;
import com.industrial.system.api.domain.SysUser;
import com.industrial.system.api.model.LoginUser;
import com.industrial.system.api.domain.AdminUser;
import com.industrial.system.api.domain.EmEnterpriseInformationCollection;
import com.industrial.system.api.domain.EmEnterpriseProduct;
import com.industrial.white.domain.dto.EnterExportDto;
import com.industrial.white.domain.vo.ChooseField;
import com.industrial.white.mapper.EmEnterpriseInformationCollectionMapper;
import com.industrial.white.mapper.WhiteIndustrialAreaMapper;
import com.industrial.white.service.IEmEnterpriseInformationCollectionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 企业基本信息ServiceImpl
 *
 * @author ruoyi
 * @date 2023-08-15
 */
@Service
public class EmEnterpriseInformationCollectionServiceImpl implements IEmEnterpriseInformationCollectionService {

    @Autowired
    private EmEnterpriseInformationCollectionMapper emEnterpriseInformationCollectionMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private WhiteIndustrialAreaMapper whiteIndustrialAreaMapper;

    Set<String> enterField = new HashSet<>();

    @Autowired
    private RemoteUserService remoteUserService;
    Set<String> proectField = new HashSet<>();

    @PostConstruct
    public void init(){

        proectField.add("pro_name");
        proectField.add("pro_specs");
        proectField.add("pro_dfp");
        proectField.add("pro_ac");
        proectField.add("pro_domain");
        proectField.add("pro_supplier");
        proectField.add("pro_user");
        proectField.add("pro_nxl");

        enterField.add("enter_name");
        enterField.add("enter_usci");
        enterField.add("enter_province");
        enterField.add("enter_city");
        enterField.add("enter_county");
        enterField.add("enter_specific_address");
        enterField.add("enter_contact_title");
        enterField.add("enter_contacts");
        enterField.add("enter_contacts_phone");
        enterField.add("enter_type");
        enterField.add("enter_scale");
        enterField.add("enter_category");
        enterField.add("enter_rfi");
        enterField.add("is_original_whitelist");
        enterField.add("recomm_level");
        enterField.add("remark");
    }

    /**
     * 获取企业信息
     *
     * @return
     */
    @Override
    public EmEnterpriseInformationCollection getEnterDataInfo() {
        //企业用户的用户名就是统一社会信用代码
        String enterUsci = SecurityUtils.getUsername();
        if(StringUtils.isBlank(enterUsci)){
            throw new RuntimeException("当前你可能没有登录");
        }
        EmEnterpriseInformationCollection e = this.emEnterpriseInformationCollectionMapper.getEnterDataInfo(enterUsci);
        if(Objects.isNull(e)){
            return new EmEnterpriseInformationCollection();
        }
        List<EmEnterpriseProduct> p = this.emEnterpriseInformationCollectionMapper.selectEmenterpriseProductList(e.getBaseId());
        if(p != null && !p.isEmpty()){
            for(EmEnterpriseProduct item : p){
                item.setProDomainStr(DictUtils.getDictLabel("bus_pro_domain",item.getProDomain()));
//                item.setProDomainStr(dictDataUtil.getBusProDomainMapRever().get(item.getProDomain()));
            }
        }
        e.setEmEnterpriseProductList(p);

//        e.setEnterCityId(e.getEnterCity());
//        e.setEnterCountyId(e.getEnterCounty());
//        e.setEnterProvinceId(e.getEnterProvince());

        e.setEnterProvince(e.getEnterProvince());
        e.setEnterCity(e.getEnterCity());
        e.setEnterCounty(e.getEnterCounty());
//
//        e.setEnterProvince((String) redisTemplate.opsForHash().get("adn",e.getEnterProvince()));
//        e.setEnterCity((String) redisTemplate.opsForHash().get("adn",e.getEnterCity()));
//        e.setEnterCounty((String) redisTemplate.opsForHash().get("adn",e.getEnterCounty()));

        String adCheckCState = e.getAdCheckCState();
        String adCheckCityState = e.getAdCheckCityState();
        String adCheckPState = e.getAdCheckPState();

        if(StringUtils.equals(adCheckPState,"0")){
            e.setMessage("省级通过审核");
        }else if(StringUtils.equals(adCheckPState,"1")){
            e.setMessage("省级驳回");
        }else if(StringUtils.equals(adCheckCityState,"0")){
            e.setMessage("市级通过审核");
        }else if(StringUtils.equals(adCheckCityState,"1")){
            e.setMessage("市级驳回");
        }else if(StringUtils.equals(adCheckCState,"0")){
            e.setMessage("县级通过审核");
        }else if(StringUtils.equals(adCheckCState,"1")){
            e.setMessage("县级驳回");
        }else{
            e.setMessage("未审核");
        }

        if(StringUtils.equals(adCheckCState,"1")){
            //为true可以修改
            e.setEdit(true);
        }else{
            e.setEdit(false);
        }

        return e;
    }

    /**
     * 查询企业基本信息列表
     *
     * @param emEnterpriseInformationCollection 企业基本信息
     * @return 企业基本信息集合
     */
    @Override
    public List<EmEnterpriseInformationCollection> selectEmEnterpriseInformationCollectionList(EmEnterpriseInformationCollection emEnterpriseInformationCollection) {
        if(StringUtils.isBlank(emEnterpriseInformationCollection.getState())){
            throw new RuntimeException("没有找到状态");
        }

        SysUser user = SecurityUtils.getLoginUser().getSysUser();
//        if(ArrayUtil.isEmpty(user.getRoles())){
//            throw new RuntimeException("当前用户没有绑定角色");
//        }

        List<String> roleArgs = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
//        if(!ArrayUtil.contains(roleArgs.toArray(),"admin")){
        if(!user.isAdmin()){
            if(ArrayUtil.contains(roleArgs.toArray(),"q_01_001")){ //企业
                emEnterpriseInformationCollection.setBaseCreateBy(user.getUserId());
            }else if(ArrayUtil.contains(roleArgs.toArray(),"x_01_011")){ //县
                emEnterpriseInformationCollection.setEnterCounty(user.getDistrictId());
                emEnterpriseInformationCollection.setAdCheckCState(emEnterpriseInformationCollection.getState());
            }else if(ArrayUtil.contains(roleArgs.toArray(),"s_01_011")){ //市
                emEnterpriseInformationCollection.setEnterCity(user.getCityId());
                if(StringUtils.equals(emEnterpriseInformationCollection.getState(),"1")){
                    emEnterpriseInformationCollection.setAdCheckCityState(emEnterpriseInformationCollection.getState());
                } else if (StringUtils.equals(emEnterpriseInformationCollection.getState(),"2") || StringUtils.equals(emEnterpriseInformationCollection.getState(),"0")) {
                    emEnterpriseInformationCollection.setAdCheckCState("0");
                    emEnterpriseInformationCollection.setAdCheckCityState(emEnterpriseInformationCollection.getState());
                }
            }else if(ArrayUtil.containsAny(roleArgs.toArray(),"p_01_011","outsize")){   //省
                if(StringUtils.equals(emEnterpriseInformationCollection.getState(),"1")){
                    emEnterpriseInformationCollection.setAdCheckPState(emEnterpriseInformationCollection.getState());
                }else if (StringUtils.equals(emEnterpriseInformationCollection.getState(),"2") || StringUtils.equals(emEnterpriseInformationCollection.getState(),"0")){
                    emEnterpriseInformationCollection.setAdCheckCState("0");
                    emEnterpriseInformationCollection.setAdCheckCityState("0");
                    emEnterpriseInformationCollection.setAdCheckPState(emEnterpriseInformationCollection.getState());
                }
                emEnterpriseInformationCollection.setEnterProvince(user.getProvinceId());
            }else{
                throw new RuntimeException("没有找到用户角色信息");
            }
        }else{
            emEnterpriseInformationCollection.setAdCheckCState(emEnterpriseInformationCollection.getState());
            emEnterpriseInformationCollection.setAdCheckCityState(emEnterpriseInformationCollection.getState());
            emEnterpriseInformationCollection.setAdCheckPState(emEnterpriseInformationCollection.getState());
        }

        emEnterpriseInformationCollection.setState("0");
        List<EmEnterpriseInformationCollection> emEnterpriseInformationCollections = new ArrayList<>();
        if(StringUtils.isNotBlank(emEnterpriseInformationCollection.getProDomain())){
            emEnterpriseInformationCollections = emEnterpriseInformationCollectionMapper.selectEmEnterpriseInformationCollectionListByDoMain(emEnterpriseInformationCollection);
        }else{
            emEnterpriseInformationCollections = emEnterpriseInformationCollectionMapper.selectEmEnterpriseInformationCollectionList(emEnterpriseInformationCollection);
        }

        for(EmEnterpriseInformationCollection item : emEnterpriseInformationCollections){
            item.setEnterCityId(item.getEnterCity());
            item.setEnterCountyId(item.getEnterCounty());
            item.setEnterProvinceId(item.getEnterProvince());

            item.setEnterProvince((String) redisTemplate.opsForHash().get("adnbaseid", item.getEnterProvince()));
            item.setEnterCity((String) redisTemplate.opsForHash().get("adnbaseid", item.getEnterCity()));
            item.setEnterCounty((String) redisTemplate.opsForHash().get("adnbaseid", item.getEnterCounty()));

            if(user.isAdmin()){
                String adCheckCState = item.getAdCheckCState();
                String adCheckCityState = item.getAdCheckCityState();
                String adCheckPState = item.getAdCheckPState();
                if (StringUtils.isNotBlank(adCheckPState) && StringUtils.equals(adCheckPState, "0")) {
                    item.setState("省级审核通过");
                } else if (StringUtils.isNotBlank(adCheckPState) && StringUtils.equals(adCheckPState, "1")) {
                    item.setState("省级审核不通过");
                } else if (StringUtils.isNotBlank(adCheckCityState) && StringUtils.equals(adCheckCityState, "0")) {
                    item.setState("市级审核通过");
                } else if (StringUtils.isNotBlank(adCheckCityState) && StringUtils.equals(adCheckCityState, "1")) {
                    item.setState("市级审核不通过");
                } else if (StringUtils.isNotBlank(adCheckCState) && StringUtils.equals(adCheckCState, "0")) {
                    item.setState("县级审核通过");
                } else if (StringUtils.isNotBlank(adCheckCState) && StringUtils.equals(adCheckCState, "1")) {
                    item.setState("县级审核不通过");
                }

            }else{
                if (ArrayUtil.containsAny(roleArgs.toArray(), "q_01_001")) {
                    String adCheckCState = item.getAdCheckCState();
                    String adCheckCityState = item.getAdCheckCityState();
                    String adCheckPState = item.getAdCheckPState();
                    if (StringUtils.isNotBlank(adCheckPState) && StringUtils.equals(adCheckPState, "0")) {
                        item.setState("省级审核通过");
                    } else if (StringUtils.isNotBlank(adCheckPState) && StringUtils.equals(adCheckPState, "1")) {
                        item.setState("省级审核不通过");
                    } else if (StringUtils.isNotBlank(adCheckCityState) && StringUtils.equals(adCheckCityState, "0")) {
                        item.setState("市级审核通过");
                    } else if (StringUtils.isNotBlank(adCheckCityState) && StringUtils.equals(adCheckCityState, "1")) {
                        item.setState("市级审核不通过");
                    } else if (StringUtils.isNotBlank(adCheckCState) && StringUtils.equals(adCheckCState, "0")) {
                        item.setState("县级审核通过");
                    } else if (StringUtils.isNotBlank(adCheckCState) && StringUtils.equals(adCheckCState, "1")) {
                        item.setState("县级审核不通过");
                    }
                } else if (ArrayUtil.contains(roleArgs.toArray(), "x_01_011")) {
                    String adCheckCState = item.getAdCheckCState();
                    if (StringUtils.equals(adCheckCState, "2")) {
                        item.setState("未审核");
                    } else if (StringUtils.equals(adCheckCState, "0")) {
                        item.setState("审核通过");
                    } else if (StringUtils.equals(adCheckCState, "1")) {
                        item.setState("驳回");
                    }
                } else if (ArrayUtil.contains(roleArgs.toArray(), "s_01_011")) {
                    String adCheckCityState = item.getAdCheckCityState();
                    if (StringUtils.equals(adCheckCityState, "2")) {
                        item.setState("未审核");
                    } else if (StringUtils.equals(adCheckCityState, "0")) {
                        item.setState("审核通过");
                    } else if (StringUtils.equals(adCheckCityState, "1")) {
                        item.setState("驳回");
                    }
                } else if (ArrayUtil.containsAny(roleArgs.toArray(), "p_01_011","outsize")) {
                    String adCheckPState = item.getAdCheckPState();
                    if (StringUtils.equals(adCheckPState, "2")) {
                        item.setState("未审核");
                    } else if (StringUtils.equals(adCheckPState, "0")) {
                        item.setState("审核通过");
                    } else if (StringUtils.equals(adCheckPState, "1")) {
                        item.setState("驳回");
                    }
                }
            }


        }

        return emEnterpriseInformationCollections;
    }


    /**
     * 查询企业基本信息
     *
     * @param baseId 企业基本信息主键
     * @return 企业基本信息
     */
    @Override
    public EmEnterpriseInformationCollection selectEmEnterpriseInformationCollectionByBaseId(String baseId) {
        EmEnterpriseInformationCollection em = emEnterpriseInformationCollectionMapper.selectEmEnterpriseInformationCollectionByBaseId(baseId);
        List<EmEnterpriseProduct> productList = this.emEnterpriseInformationCollectionMapper.selectEmenterpriseProductByEnterId(em.getBaseId());

        if(productList != null && !productList.isEmpty()){
            for(EmEnterpriseProduct item : productList){
                item.setProDomainStr(DictUtils.getDictLabel("bus_pro_domain",item.getProDomain()));
//                item.setProDomainStr(dictDataUtil.getBusProDomainMapRever().get(item.getProDomain()));
            }
        }
        em.setEmEnterpriseProductList(productList);
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        List<String> roles = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(!roles.isEmpty()){
            if(ArrayUtil.contains(roles.toArray(),"s_01_011")
                    || ArrayUtil.contains(roles.toArray(),"p_01_011")
                    || ArrayUtil.contains(roles.toArray(),"x_01_011")){
                em.setEdit(true);
            }
        }else{
            em.setEdit(false);
        }

        return em;
    }

    /**
     * 导出表格
     *
     * @param enterParams
     * @return
     */
    @Override
    public List<EnterExportDto> selectExportEnterData(EmEnterpriseInformationCollection enter) {
        if(StringUtils.isBlank(enter.getState())){
            throw new RuntimeException("没有找到需要导出数据的状态");
        }
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("请先登录");
        }
        SysUser user = loginUser.getSysUser();

        List<String> roleArgs = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(ArrayUtil.contains(roleArgs.toArray(),"x_01_011")){  //县
            enter.setEnterCounty(user.getDistrictId());
            enter.setAdCheckCState(enter.getState());
        }else if(ArrayUtil.contains(roleArgs.toArray(),"s_01_011")){
            enter.setEnterCity(user.getCityId());
            if(StringUtils.equals(enter.getState(),"1")){
                enter.setAdCheckCityState(enter.getState());
                //2是审核通过，0是待审核，1是驳回
            } else if (StringUtils.equals(enter.getState(),"2") || StringUtils.equals(enter.getState(),"0")) {
                enter.setAdCheckCState("0");
                enter.setAdCheckCityState(enter.getState());
            }
        }else if(ArrayUtil.contains(roleArgs.toArray(),"p_01_011")){
            if(StringUtils.equals(enter.getState(),"1")){
                enter.setAdCheckPState(enter.getState());
            }else if (StringUtils.equals(enter.getState(),"2") || StringUtils.equals(enter.getState(),"0")){
                enter.setAdCheckCState("0");
                enter.setAdCheckCityState("0");
                enter.setAdCheckPState(enter.getState());
            }
            enter.setEnterProvince(user.getProvinceId());
        }else{
            throw new RuntimeException("当前用户不是【省、市、县】级别用户，没有导出权限");
        }
        enter.setState("0");
        List<EnterExportDto> result = emEnterpriseInformationCollectionMapper.selectEnterDataList(enter);
        if(!result.isEmpty()){
            for(int i = 0;i< result.size();i++){
                EnterExportDto enterExportDto = result.get(i);
                enterExportDto.setXh(String.valueOf(i + 1));

                if(StringUtils.isNotBlank(enterExportDto.getProDomain())){
                    enterExportDto.setProDomain(DictUtils.getDictLabel("bus_pro_domain",enterExportDto.getProDomain()));
                }
                if(StringUtils.isNotBlank(enterExportDto.getEnterRfi())){
                    enterExportDto.setEnterRfi(DictUtils.getDictLabel("bus_enter_rfi",enterExportDto.getEnterRfi()));
                }
                if(StringUtils.isNotBlank(enterExportDto.getEnterType())){
                    enterExportDto.setEnterType(DictUtils.getDictLabel("bus_enter_type",enterExportDto.getEnterType()));
                }
                if(StringUtils.isNotBlank(enterExportDto.getEnterScale())){
                    enterExportDto.setEnterScale(DictUtils.getDictLabel("bus_enter_scale",enterExportDto.getEnterScale()));
                }
                if(StringUtils.isNotBlank(enterExportDto.getEnterCategory())){
                    enterExportDto.setEnterCategory(DictUtils.getDictLabel("bus_national_economy_classification",enterExportDto.getEnterCategory()));
                }
                if(StringUtils.isNotBlank(enterExportDto.getRecommLevel())){
                    enterExportDto.setRecommLevel(DictUtils.getDictLabel("recomm_level",enterExportDto.getRecommLevel()));
                }


//                enterExportDto.setProDomain(dictDataUtil.getBusProDomainMapRever().get(enterExportDto.getProDomain()));
//                enterExportDto.setEnterRfi(dictDataUtil.getBusEnterRfiMapResver().get(enterExportDto.getEnterRfi()));
//                enterExportDto.setEnterType(dictDataUtil.getBusEnterTypeMapRever().get(enterExportDto.getEnterType()));
//                enterExportDto.setEnterScale(dictDataUtil.getBusEnterScaleMapRever().get(enterExportDto.getEnterScale()));
//                enterExportDto.setEnterCategory(dictDataUtil.getBusNationalEconomyClassificationMapResver().get(enterExportDto.getEnterCategory()));
//                enterExportDto.setRecommLevel(dictDataUtil.getBusRecommLevelMap().get(enterExportDto.getRecommLevel()));
            }
        }
        return result;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public void checkEnter(Map<String, String> params) {
        SysUser user = SecurityUtils.getLoginUser().getSysUser();
        if(ArrayUtil.isEmpty(user.getRoles())){
            throw new RuntimeException("当前用户没有绑定角色");
        }
        String baseId = params.get("baseId");
        String state = params.get("state");
        String reject = params.get("reject");
        EmEnterpriseInformationCollection eeic = new EmEnterpriseInformationCollection();
        List<String> roleArgs = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(ArrayUtil.contains(roleArgs.toArray(),"x_01_011")){
            eeic.setBaseId(baseId);
            eeic.setAdCheckCState(state);
        }else if(ArrayUtil.contains(roleArgs.toArray(),"s_01_011")){
            eeic.setBaseId(baseId);
            if(StringUtils.equals(state,"1")){
                eeic.setAdCheckCityState(state);
                eeic.setAdCheckCState(state);
            }else{
                eeic.setAdCheckCityState(state);
            }
        }else if(ArrayUtil.contains(roleArgs.toArray(),"p_01_011")){
            eeic.setBaseId(baseId);
            if(StringUtils.equals(state,"1")){
                eeic.setAdCheckPState(state);
                eeic.setAdCheckCityState(state);
                eeic.setAdCheckCState(state);
            }else{
                eeic.setAdCheckPState(state);
                if(StringUtils.equals(state,"0")){
                     //省级用户通过了审核,该企业就成为白名单企业
                    Map map = this.emEnterpriseInformationCollectionMapper.selectUsccFormEnterId(baseId);
                    if(!Objects.isNull(map)){
                        String enterUsci = String.valueOf(map.get("enter_usci"));
                        //远程调用更新用户角色
                        SysUser sysUser = new SysUser();
                        sysUser.setUserName(enterUsci);
                        remoteUserService.updateWhiteUserRole(sysUser);
                    }
                }
            }

        }else{
            throw new RuntimeException("没有找到用户角色信息");
        }
        eeic.setIsShowState("1");
        eeic.setReject(reject);
        eeic.setBaseUpdateTime(DateUtils.getNowDate());
        eeic.setBaseUpdateBy(user.getUserId());
        this.emEnterpriseInformationCollectionMapper.updateEmEnterpriseInformationCollection(eeic);

    }

    @Override
    public AjaxResult editEnter(EmEnterpriseInformationCollection enter) {
        enter.setBaseUpdateTime(DateUtils.getNowDate());
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            return AjaxResult.warn("您可能没有登录或者服务端出了未知错误");
        }

        Set<String> roleStrArgs = loginUser.getRoles();

        if(roleStrArgs.size() == 0){
            return AjaxResult.warn("没有在您的用户中找到设置的角色");
        }

        if(!ArrayUtil.containsAny(roleStrArgs.toArray(),Constants.COUNTY, Constants.CITY,Constants.PROVINCE)){
            return AjaxResult.warn(String.format("您用户并不是【%s、%s、%s】级别用户，不可以修改","区/县","市","省"));
        }

        String userid = loginUser.getUserid();
        enter.setBaseUpdateBy(userid);
        emEnterpriseInformationCollectionMapper.updateEnterpriseInformationRestrictedFields(enter);
        return AjaxResult.success();
    }

    /**
     * 修改企业基本信息
     *
     * @param emEnterpriseInformationCollection
     */
    @Override
    public int updateEmEnterpriseInformationCollection(EmEnterpriseInformationCollection emEnterpriseInformationCollection) {
        //删除产品信息
        emEnterpriseInformationCollectionMapper.deleteEmEnterpriseProductByEnterId(emEnterpriseInformationCollection.getBaseId());
        insertEmEnterpriseProduct(emEnterpriseInformationCollection);

        EmEnterpriseInformationCollection enterInfoByUsci = emEnterpriseInformationCollectionMapper.selectEmEnterpriseInforByUsciAndEnterId(emEnterpriseInformationCollection);
        if(!Objects.isNull(enterInfoByUsci)){
            throw new RuntimeException("您输入的统一社会信用代码已经被录入");
        }
        EmEnterpriseInformationCollection tempEm = emEnterpriseInformationCollectionMapper.selectEmEnterpriseInformationCollectionByBaseId(emEnterpriseInformationCollection.getBaseId());
        if(Objects.isNull(tempEm.getIsShowState())){
            emEnterpriseInformationCollection.setBaseCreateTime(DateUtils.getNowDate());
        }
        //如果等于0代表数据已经被修改,新注册的用户state是1，企业补充过数据后state修改成0
        emEnterpriseInformationCollection.setState("0");
        emEnterpriseInformationCollection.setAdCheckCState("2");
        emEnterpriseInformationCollection.setAdCheckCityState("2");
        emEnterpriseInformationCollection.setAdCheckPState("2");
        emEnterpriseInformationCollection.setIsShowState("1");
        int i = emEnterpriseInformationCollectionMapper.updateEmEnterpriseInformationCollection(emEnterpriseInformationCollection);
        return i;
    }

    private void insertEmEnterpriseProduct(EmEnterpriseInformationCollection emEnterpriseInformationCollection) {
        List<EmEnterpriseProduct> emEnterpriseProductList = emEnterpriseInformationCollection.getEmEnterpriseProductList();
        String baseId = emEnterpriseInformationCollection.getBaseId();
        if (emEnterpriseProductList != null)
        {
            List<EmEnterpriseProduct> list = new ArrayList<EmEnterpriseProduct>();
            for (EmEnterpriseProduct emEnterpriseProduct : emEnterpriseProductList)
            {
                emEnterpriseProduct.setBaseId(IdUtil.simpleUUID());
                emEnterpriseProduct.setEnterId(baseId);
                list.add(emEnterpriseProduct);
            }
            if (list.size() > 0)
            {
                emEnterpriseInformationCollectionMapper.batchEmEnterpriseProduct(list);
            }
        }

    }

    /**
     * 新增企业基本信息
     *
     * @param emEnterpriseInformationCollection 企业基本信息
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertEmEnterpriseInformationCollection(EmEnterpriseInformationCollection emEnterpriseInformationCollection) {
        if(!CreditCodeUtil.isCreditCode(emEnterpriseInformationCollection.getEnterUsci())){
            throw new RuntimeException("社会统一信用代码不合法");
        }
//        emEnterpriseInformationCollection.setIsShowState("1");
        emEnterpriseInformationCollection.setBaseId(IdUtil.simpleUUID());
        emEnterpriseInformationCollection.setAdCheckPState("2");
        emEnterpriseInformationCollection.setAdCheckCState("2");
        emEnterpriseInformationCollection.setAdCheckCityState("2");
        emEnterpriseInformationCollection.setBaseCreateTime(DateUtils.getNowDate());
        emEnterpriseInformationCollection.setBaseCreateBy(SecurityUtils.getUserId());
        //如果这个值不是空，说明是在亩产中点击的申请白名单
        if(StringUtils.isNotBlank(emEnterpriseInformationCollection.getIsPrem())){
            //如果是亩产中申请的白名单需要给用户插入白名单普通角色
            SysUser sysUser = new SysUser();
            sysUser.setUserId(SecurityUtils.getUserId());
            sysUser.setRoleId("a232ec59dab040aaabfce8b4a0eba3f7");
            remoteUserService.insertUserRole(sysUser);
            emEnterpriseInformationCollection.setIsShowState("1");
            emEnterpriseInformationCollection.setState("0");
        }
        int rows = emEnterpriseInformationCollectionMapper.insertEmEnterpriseInformationCollection(emEnterpriseInformationCollection);
        insertEmEnterpriseProduct(emEnterpriseInformationCollection);


        return rows;
    }

    /**
     * 查询当前登录用户的信息
     *
     * @return
     */
    @Override
    public AdminUser selectCurrentLoginUserInfo() {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("没有找到当前登录用户的信息，无法导出");
        }
        String userId = loginUser.getUserid();
        R<SysUser> remoteUserInfo = remoteUserService.getUserInfoByUserId(userId);
        if(remoteUserInfo.getCode() != R.SUCCESS){
            throw new RuntimeException("未查找到该用户信息");
        }

        AdminUser adminUser = new AdminUser();
        SysUser data = remoteUserInfo.getData();
        adminUser.setUserName(data.getUserName());
        adminUser.setPhonennumber(data.getPhonenumber());
        adminUser.setLandLine(data.getLandLine());
        adminUser.setDuties(data.getDuties());

        List<SysRole> roles = loginUser.getSysUser().getRoles();
        List<String> roleArgs = roles.stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(ArrayUtil.contains(roleArgs.toArray(),Constants.CITY)){
            String city = loginUser.getSysUser().getCityId();
            adminUser.setCity((String) redisTemplate.opsForHash().get("adn",city));
        }else if(ArrayUtil.contains(roleArgs.toArray(),Constants.PROVINCE)){
            String sheng = loginUser.getSysUser().getProvinceId();
            adminUser.setCity((String) redisTemplate.opsForHash().get("adn",sheng));
        }else if(ArrayUtil.contains(roleArgs.toArray(),Constants.COUNTY)){
            String xian = loginUser.getSysUser().getDistrictId();
            adminUser.setCity((String) redisTemplate.opsForHash().get("adn",xian));
        }
        return adminUser;
    }

    /**
     * 判断亩产的企业是否存在白名单中
     *
     * @param uscc
     * @return
     */
    @Override
    public Boolean preMuExistWhite(String uscc) {
        List<EmEnterpriseInformationCollection> result = emEnterpriseInformationCollectionMapper.selectEmEnterpriseInforByUscc(uscc);
        if(result == null || result.isEmpty()){
            return true;
        }
        return false;
    }

    @Override
    public List<EnterExportDto> selectChooseFiedldData(ChooseField chooseField, EmEnterpriseInformationCollection enter) {
        if(chooseField.getFieldArgs() == null || chooseField.getFieldArgs().isEmpty()){
            throw new RuntimeException("并没有找到要导出的字段");
        }

        LoginUser loginUser = SecurityUtils.getLoginUser();
        if(Objects.isNull(loginUser)){
            throw new RuntimeException("请先登录");
        }

        SysUser user = loginUser.getSysUser();
        List<String> roleArgs = user.getRoles().stream().map(item -> item.getRoleKey()).collect(Collectors.toList());
        if(ArrayUtil.contains(roleArgs.toArray(),"x_01_011")){
            enter.setEnterCounty(user.getDistrictId());
            enter.setAdCheckCState(enter.getState());
        }else if(ArrayUtil.contains(roleArgs.toArray(),"s_01_011")){
            enter.setEnterCity(user.getCityId());
            if(StringUtils.equals(enter.getState(),"1")){
                enter.setAdCheckCityState(enter.getState());
                //2是审核通过，0是待审核，1是驳回
            } else if (StringUtils.equals(enter.getState(),"2") || StringUtils.equals(enter.getState(),"0")) {
                enter.setAdCheckCState("0");
                enter.setAdCheckCityState(enter.getState());
            }
        }else if(ArrayUtil.contains(roleArgs.toArray(),"p_01_011")){
            if(StringUtils.equals(enter.getState(),"1")){
                enter.setAdCheckPState(enter.getState());
            }else if (StringUtils.equals(enter.getState(),"2") || StringUtils.equals(enter.getState(),"0")){
                enter.setAdCheckCState("0");
                enter.setAdCheckCityState("0");
                enter.setAdCheckPState(enter.getState());
            }
            enter.setEnterProvince(user.getProvinceId());
        }else{
            throw new RuntimeException("当前用户不是【省、市、县】级别用户，没有导出权限");
        }

        String sql = genSelectEnterProDataSql(chooseField.getFieldArgs());
        List<EnterExportDto> result = this.emEnterpriseInformationCollectionMapper.selectEnterProDataFromGenSql(sql,enter);
        if(!result.isEmpty()){
            for(int i = 0;i< result.size();i++){
                EnterExportDto enterExportDo = result.get(i);
                enterExportDo.setXh(String.valueOf(i + 1));

                if(StringUtils.isNotBlank(enterExportDo.getProDomain())){
                    enterExportDo.setProDomain(DictUtils.getDictLabel("bus_pro_domain",enterExportDo.getProDomain()));
                }

                if(StringUtils.isNotBlank(enterExportDo.getEnterRfi())){
                    enterExportDo.setEnterRfi(DictUtils.getDictLabel("bus_enter_rfi",enterExportDo.getEnterRfi()));
                }
                if(StringUtils.isNotBlank(enterExportDo.getEnterType())){
                    enterExportDo.setEnterType(DictUtils.getDictLabel("bus_enter_type",enterExportDo.getEnterType()));
                }
                if(StringUtils.isNotBlank(enterExportDo.getEnterScale())){
                    enterExportDo.setEnterScale(DictUtils.getDictLabel("bus_enter_scale",enterExportDo.getEnterScale()));
                }
                if(StringUtils.isNotBlank(enterExportDo.getEnterCategory())){
                    enterExportDo.setEnterCategory(DictUtils.getDictLabel("bus_national_economy_classification",enterExportDo.getEnterCategory()));
                }
                if(StringUtils.isNotBlank(enterExportDo.getRecommLevel())){
                    enterExportDo.setRecommLevel(DictUtils.getDictLabel("recomm_level",enterExportDo.getRecommLevel()));
                }



//                enterExportDo.setProDomain(dictDataUtil.getBusProDomainMapRever().get(enterExportDo.getProDomain()));
//                enterExportDo.setEnterRfi(dictDataUtil.getBusEnterRfiMapResver().get(enterExportDo.getEnterRfi()));
//                enterExportDo.setEnterType(dictDataUtil.getBusEnterTypeMapRever().get(enterExportDo.getEnterType()));
//                enterExportDo.setEnterScale(dictDataUtil.getBusEnterScaleMapRever().get(enterExportDo.getEnterScale()));
//                enterExportDo.setEnterCategory(dictDataUtil.getBusNationalEconomyClassificationMapResver().get(enterExportDo.getEnterCategory()));
//                enterExportDo.setRecommLevel(dictDataUtil.getBusRecommLevelMap().get(enterExportDo.getRecommLevel()));
            }
        }
        return result;
    }

    private String genSelectEnterProDataSql(List<String> fieldArgs) {
        //标识，用于判断是否存在企业或产品的字段，用于后面拼接sql添加表用
        boolean existEnter = false;
        boolean existProect = false;

        StringBuilder sqlBuilder = new StringBuilder("select ");
        for(String item : fieldArgs){
            if(enterField.contains(item)){
                existEnter = true;
                sqlBuilder.append("eeic.").append(item).append(",");
            }else if(proectField.contains(item)){
                existProect = true;
                sqlBuilder.append("eep.").append(item).append(",");
            }
        }
        /**
         * 这里加入社会统一信用代码的原因是
         * 在后面进行单元格合并的时候是通过判断
         * 的社会统一代码是否一致来进行合并的
         */
        if(existEnter){
            if(!ArrayUtil.contains(fieldArgs.toArray(),"enter_usci")){
                sqlBuilder.append("eeic.").append("enter_usci,");
            }
        }

        sqlBuilder.deleteCharAt(sqlBuilder.length() - 1);
        /**
         * 分支一：这个分支是当企业的字段和产品的字段都存在的时候，这个时候在进行sql拼接的时候需要进行联表查询
         * 分支二：当只有企业的字段的时候不需要进行联表查询
         * 分支三：当只有产品的字段的时候也不需要进行联表查询
         */
        if(existEnter && existProect){
            sqlBuilder.append(" from white_industrial_enterprise as eeic ");
            sqlBuilder.append(" LEFT JOIN white_industrial_product AS eep ON eeic.base_id = eep.enter_id ");
        }else if(existEnter){
            sqlBuilder.append(" from white_industrial_enterprise as eeic ");
        }else if(existProect){
            sqlBuilder.append(" from white_industrial_product as eep ");
        }else{
            throw new RuntimeException("导出前请选择字段");
        }
        return sqlBuilder.toString();
    }

    @Override
    public void savePreMuCompanyInfoToWhite(Map<String, Object> params) {
        EmEnterpriseInformationCollection p = new EmEnterpriseInformationCollection();

        p.setBaseId(IdUtil.simpleUUID());
        String uscc = (String)params.get("uscc");
        p.setEnterUsci(uscc);
        String companyName = (String)params.get("companyName");
        p.setEnterName(companyName);

        String companyScale = (String)params.get("companyScale");
        p.setEnterScale(companyScale);

        String contact = (String)params.get("contact");
        p.setEnterContacts(contact);

        String phone = (String)params.get("phone");
        p.setEnterContactsPhone(phone);

        String detailAddr = (String)params.get("detailAddr");
        p.setEnterSpecificAddress(detailAddr);

        p.setState("1");
        p.setAdCheckCityState("2");
        p.setAdCheckCState("2");
        p.setAdCheckPState("2");

        String province = (String)params.get("province");
        String city = (String)params.get("city");
        String county = (String)params.get("county");

        if(StringUtils.isNotBlank(province)){
            String value = whiteIndustrialAreaMapper.loadAdCodeToAdBaseId(province);
            p.setEnterProvince(value);
        }
        if(StringUtils.isNotBlank(city)){
            String value = whiteIndustrialAreaMapper.loadAdCodeToAdBaseId(city);
            p.setEnterCity(value);
        }
        if(StringUtils.isNotBlank(county)){
            String value = whiteIndustrialAreaMapper.loadAdCodeToAdBaseId(county);
            p.setEnterCounty(value);
        }

        emEnterpriseInformationCollectionMapper.insertEmEnterpriseInformationCollection(p);

        SysUser sysUser = new SysUser();
        sysUser.setUserId(SecurityUtils.getUserId());
        sysUser.setRoleId("a232ec59dab040aaabfce8b4a0eba3f7");
        R<Boolean> booleanR = remoteUserService.insertUserRole(sysUser);
        if(booleanR.getCode() != R.SUCCESS){
            System.out.println("------> 用户角色写入失败");
        }
    }

    /**
     * 查询传入USCC是否存在白名单中
     *
     * @param uscc
     * @return
     */
    @Override
    public List<String> preMuExistWhiteByUscc(List<String> uscc) {
        List<EmEnterpriseInformationCollection> emEnterpriseInformationCollections = emEnterpriseInformationCollectionMapper.preMuExistWhiteByUscc(uscc);
        if(emEnterpriseInformationCollections != null && !emEnterpriseInformationCollections.isEmpty()){
            List<String> collect = emEnterpriseInformationCollections.stream().map(EmEnterpriseInformationCollection::getEnterUsci).collect(Collectors.toList());
            return collect;
        }
        return new ArrayList<String>();
    }

    /**
     * <p>
     *  通过企业信息代码查询企业信息
     * </p>
     *
     * @param uscc
     * @return
     */
    @Override
    public EmEnterpriseInformationCollection queryWhiteInfoByUscc(String uscc) {
        return emEnterpriseInformationCollectionMapper.queryWhiteInfoByUscc(uscc);
    }
}
